package cn.datawin.task.process;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

import cn.datawin.spider.page.Page;
import cn.datawin.spider.processor.Processor;
import cn.datawin.spider.seletor.Html;
import cn.datawin.task.Rule;
import cn.datawin.task.util.HtmlImg;
import cn.datawin.task.util.SpiderUtil;

public abstract class AbstractProcessor implements Processor {

	Map<String, Object> params;

	protected void parseRule(Rule rule, Page page) {
		List<Map<String, String>> expression = rule.getExpression();
		if(expression == null) return;
		for (Map<String, String> map : expression) {
			Html html = page.getHtml();
			/*添加 ImgCut 功能*/
			HtmlImg Imghtml = new HtmlImg();
			Imghtml.setUrl(page.getHttpRequest().getUrl());
			 /* 用于执行 js 的判断 */
			if(Boolean.valueOf(map.remove("execjs"))){ 
				List<Cookie> cookies =  ((DefaultHttpClient)page.getHttpService()).getCookieStore().getCookies();
//				cookies.remove(0);
				Imghtml.execjs(cookies);
			}else{
				Imghtml.setElements(html.getElements());
			}
			
			String n = map.remove("name");
			Set<String> sets = map.keySet();
			Iterator<String> ite = sets.iterator();
			while (ite.hasNext()) {
				String type = ite.next();
				String value = map.get(type);
				Method me = SpiderUtil.getHtmlMethod(type);
				Object result = null;
				if(StringUtils.isEmpty(value)){
					result = SpiderUtil.invokeMethod(me, Imghtml);
				}else{
					result = SpiderUtil.invokeMethod(me, Imghtml, value);
				}
				if (!ite.hasNext()) {
					if(result == null || result.toString().isEmpty()){
						continue;
					}
					params.put(n, result);
				}
			}
			map.put("name", n);
		}
	}

}
